<template>
  <div v-for="(blog, index) in blogListInfo" style="margin-bottom: 15px">
    <n-card :title="blog.title">
      {{ blog.content }}

      <template #footer>
        <n-space align="center">
          <div>发布时间：{{ blog.create_time }}</div>
          <n-button @click="toUpdate(blog)">修改</n-button>
          <n-button @click="toDelete(blog)">删除</n-button>
        </n-space>
      </template>
    </n-card>
  </div>
  <n-space>
    <div @click="toPage(pageNum)" v-for="pageNum in pageInfo.pageCount">
      <div
        :style="{
          color: pageNum === pageInfo.page ? 'blue' : '',
          cursor: 'pointer',
        }"
      >
        {{ pageNum }}
      </div>
    </div>
  </n-space>
</template>
<script setup>
import { ref, reactive, onMounted, inject } from "vue";
const blogListInfo = ref([]);
const axios = inject("axios");
const dialog = inject("dialog");
const message = inject("message");
const emit = defineEmits(['edit-blog'])

//分页数据
const pageInfo = reactive({
  page: 1, // 当前页码
  pageSize: 3, // 页长
  pageCount: 0, // 页数
  count: 0, // 总数
});

onMounted(() => {
  loadBlogs();
});

//读取博客列表
const loadBlogs = async () => {
  let res = await axios.get(
    `/blog/search?page=${pageInfo.page}&pageSize=${pageInfo.pageSize}`
  );
  let temp_rows = res.data.data.rows;
  for (let row of temp_rows) {
    row.content += "...";
    let d = new Date(row.create_time);
    row.create_time = `${d.getFullYear()}年${
      d.getMonth() + 1
    }月${d.getDate()}日`;
  }
  blogListInfo.value = temp_rows;
  pageInfo.count = res.data.data.count;
  //   pageInfo.pageCount =
  //     parseInt(pageInfo.count / pageInfo.pageSize) +
  //     (pageInfo.count % pageInfo.pageSize > 0 ? 1 : 0);
  pageInfo.pageCount = Math.ceil(pageInfo.count / pageInfo.pageSize);
  // console.log(res);
};

const toPage = async (pageNum) => {
  pageInfo.page = pageNum;
  loadBlogs();
};

const toUpdate = (blog) => {
    const {id} = blog
    emit('edit-blog',id)

};
const toDelete = (blog) => {
  try {
    dialog.warning({
      title: "警告",
      content: "是否要删除",
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: async () => {
        let res = await axios.delete(`/blog/_token/delete?id=${blog.id}`);
        if (res.data.code == 200) {
          loadBlogs();
          message.info(res.data.msg);
        } else {
          message.error(res.data.msg);
        }
      },
      onNegativeClick: () => {},
    });
  } catch (err) {}
};
</script>
<style lang="scss"></style>
